package com.wuda.servlet;

import com.wuda.bean.User;
import com.wuda.dao.UserDao;
import com.wuda.utils.Util;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;


@WebServlet("/enroll")
public class Enroll extends HttpServlet {
	UserDao userDao = new UserDao();
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf8");
		PrintWriter out = response.getWriter();

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");

		// 设置响应map
		HashMap<String, Object> hashMap = new HashMap<>();

		try {
			// 验证邮箱有效性
			if (!Util.isValidEmail(email)) {
				hashMap.put("code", 201);
				hashMap.put("msg", "无效的邮箱地址");
				JSONObject json = JSONObject.fromObject(hashMap);
				out.write(json.toString());
				return;
			}
			// 检查是否已存在相同的邮箱
			if (userDao.isEmailExists(email)) {
				hashMap.put("code", 201);
				hashMap.put("msg", "邮箱已存在");
				JSONObject json = JSONObject.fromObject(hashMap);
				out.write(json.toString());
				return;
			}

			String encryptedPassword = Util.passMd5(password);

			User user = new User();
			user.setUsername(username);
			user.setPassword(encryptedPassword);
			user.setEmail(email);

			boolean isSaved = userDao.saveUser(user);
			if (isSaved) {
				hashMap.put("code", 200);
				hashMap.put("msg", "注册成功");
				hashMap.put("url", request.getContextPath() + "/login.jsp");
			} else {
				hashMap.put("code", 201);
				hashMap.put("msg", "注册失败");
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			hashMap.put("code", 500);
			hashMap.put("msg", "数据库操作错误");
		}

		JSONObject json = JSONObject.fromObject(hashMap);
		out.write(json.toString());
	}
}
